package com.enation.pangu.task.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.enation.pangu.model.Step;
import com.enation.pangu.monitor.MonitorService;
import com.enation.pangu.ssh.SshClient;
import com.enation.pangu.task.StepExecutor;
import com.enation.pangu.utils.StringUtil;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

/**
 * reids 命令执行器
 * @author kingapex
 * @version 1.0
 * @data 2022/7/4 22:24
 **/
@Service("redis_flush")
public class RedisStepExecutor implements StepExecutor {

    Logger logger= LoggerFactory.getLogger(MysqlStepExecutor.class);
    @Autowired
    private MonitorService monitorService;
    @Override
    public boolean execute(Step step, Map env, SshClient sshClient) {
        String executorParams =step.getExecutorParams();
        if (StringUtil.notEmpty(executorParams)) {
            Map<String, String> param = (Map<String, String>) JSONUtils.parse(executorParams);

            try {
                executeSql(param);
            } catch (Exception e) {
                e.printStackTrace();
                monitorService.appendMachineLog("reids flushdb执行出错");

                logger.error("mysql sql execute error",e);
                return false;
            }

        }

        return true;
    }


    private void executeSql(Map<String, String> param) throws SQLException, FileNotFoundException {
        String host = param.get("host");
        String port = param.get("port");
        String password = param.get("password");
        String database = param.get("database");

        //连接本地的 Redis 服务
        Jedis jedis = new Jedis(host,StringUtil.toInt(port,6379));

        // 如果 Redis 服务设置了密码，需要下面这行，没有就不需要
        if (!StringUtil.isEmpty(password)) {
            jedis.auth(password);
        }

        jedis.select(StringUtil.toInt(database, 0));


        monitorService.appendMachineLog("redis连接成功");

//        jedis.eval(command);

        jedis.flushDB();

        monitorService.appendMachineLog("命令执行成功");

    }
    public static void main(String[] args) {
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("192.168.2.186",6379);
        // 如果 Redis 服务设置了密码，需要下面这行，没有就不需要
        jedis.auth("123456");
        System.out.println("连接成功");

        //查看服务是否运行
        System.out.println("服务正在运行: "+jedis.ping());
    }

}
